package cn.net.isir.core;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author liuxubo
 * @filename ASfd.java
 * @package cn.net.isir.core
 * @email lxb@isir.net.cn
 * @date 2018/11/09
 * @comment
 * @since 1.8
 */
@Component
public class SpringApplicationContextUtils implements ApplicationContextAware {
    // 声明log4j日志
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(SpringApplicationContextUtils.class);

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info(applicationContext);
        SpringApplicationContextUtils.applicationContext = applicationContext;
//        logger.info(applicationContext);
//        logger.info(applicationContext);
//        logger.info(applicationContext);
//        logger.info(applicationContext);
//        logger.info(applicationContext);
    }

    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //根据名称（@Resource 注解）
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //根据类型（@Autowired）
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(name);
    }

    public static Class<? extends Object> getType(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.getType(name);
    }

    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.getAliases(name);
    }
}
